// MINI UI解析
mini.parse();

/**
 * 订单详情处理器类
 */
function OrderDetailHandler() {

}

// 实例化全局订单处理器
OrderDetailHandler.instance = new OrderDetailHandler();
OrderDetailHandler.mgrData = new OrderMgrData();
OrderDetailHandler.hiddenForm = new mini.Form("hiddenForm");
OrderDetailHandler.hiddenForm.loadingMsg = OrderDetailHandler.mgrData.operatingMsg;
OrderDetailHandler.allStatus = {boiOrder: "", boiPay: "", boiShip: ""};

// 获得所有订单流程处理控件对象
OrderDetailHandler.queRBtn = mini.get("order_detail_quer");
OrderDetailHandler.fuKBtn = mini.get("order_detail_fuk");
OrderDetailHandler.peiHBtn = mini.get("order_detail_peih");
OrderDetailHandler.faHDBtn = mini.get("order_detail_fahd");
OrderDetailHandler.quFHBtn = mini.get("order_detail_qufh");
OrderDetailHandler.shouHBtn = mini.get("order_detail_shouh");
OrderDetailHandler.tuiHBtn = mini.get("order_detail_tuih");
OrderDetailHandler.quXBtn = mini.get("order_detail_qux");
OrderDetailHandler.wuFLXBtn = mini.get("order_detail_wuflx");
OrderDetailHandler.shiXBtn = mini.get("order_detail_shix");

// 获得订单详情各面板对象
OrderDetailHandler.baseInfoPanel = mini.get("baseInfoPanel");
OrderDetailHandler.consigneePanel = mini.get("consigneePanel");
OrderDetailHandler.goodsPanel = mini.get("goodsPanel");
OrderDetailHandler.feeingPanel = mini.get("feeingPanel");
OrderDetailHandler.operatingPanel = mini.get("operatingPanel");
OrderDetailHandler.logingPanel = mini.get("logingPanel");

// 获得订单详情各表格对象
OrderDetailHandler.goodsListGrid = mini.get("goodsListGrid");
OrderDetailHandler.orderLogGrid = mini.get("orderLogGrid");

// 获得操作备注表格对象
OrderDetailHandler.$remarkTab = $("#remarkTab");
OrderDetailHandler.$lolOremark = $("#lolOremark");

// 定义订单详情页功能权限字符编码JSON		
OrderDetailHandler.purJsonOdetail ={
		queRBtn : "order_detail_quer", 
		fuKBtn : "order_detail_fuk", 
		peiHBtn : "order_detail_peih",
		faHDBtn : "order_detail_fahd", 
		quFHBtn : "order_detail_qufh", 
		shouHBtn : "order_detail_shouh", 
		tuiHBtn : "order_detail_tuih",
		quXBtn : "order_detail_qux", 
		wuFLXBtn : "order_detail_wuflx", 
		shiXBtn : "order_detail_shix",
		editConsignee : "order_detail_edit_consig",
		editOrderGoods : "order_detail_edit_goods"
};

// 定义全局变量gbConsignee，用来存储当前收货人姓名
OrderDetailHandler.gbConsignee = "";

/**
 * 根据订单在不同状态下订制的权限编码数组展示功能权限按钮
 * @param {} purArray
 */
OrderDetailHandler.loadPurviewBtn = function(purArray) {
	var userArr = MiniuiTools.isHasPurview(purArray);
	
	for (var i = 0; i < userArr.length; i++) {
		var purviewBtn = mini.get(purArray[i]);
		
		if(purviewBtn){
			purviewBtn.setVisible(userArr[i]);
		}
	}
};

/**
 * 清空操作备注文本域
 */
OrderDetailHandler.clearLolOremark = function(){
	OrderDetailHandler.$lolOremark.val("");
}

/**
 * 初始化页面控件使用状态
 */
OrderDetailHandler.initPageCtlStatus = function(){
	OrderDetailHandler.queRBtn.setVisible(false);
	OrderDetailHandler.fuKBtn.setVisible(false);
	OrderDetailHandler.peiHBtn.setVisible(false);
	OrderDetailHandler.faHDBtn.setVisible(false);
	OrderDetailHandler.quFHBtn.setVisible(false);
	OrderDetailHandler.shouHBtn.setVisible(false);
	OrderDetailHandler.tuiHBtn.setVisible(false);
	OrderDetailHandler.quXBtn.setVisible(false);
	OrderDetailHandler.wuFLXBtn.setVisible(false);
	OrderDetailHandler.shiXBtn.setVisible(false);
}

/**
 * 根据订单信息重新设置页面控件使用状态
 * 
 * 订单状态：（0-未确认，1-已确认，2-已取消，3-已结单，4-已失效）
 * 支付状态：（0-未付款，1-已付款，2-已退款）
 * 配送状态：（0-未配送，1-配货中，2-发货中，3-已发货，4-已收货，5-已退货，6-无法联系）
 * 
 * 1、下单完成时：[未确认，未付款，未发货]
 * 2、确认完成时：[已确认、未付款、未发货]
 * 3、付款完成时：[已确认，已付款，未发货]
 * 4、配货完成时：[已确认，已付款，配货中]
 * 5、发货单生成完成时：[已确认，已付款，发货中][InvoiceDetailHandler.js line 48]
 * 6、发货完成时：[已确认，已付款，已发货]
 * 
 * 7、退货：[已确认，已付款，已退货]
 * 8、无法联系：[已确认，已付款，无法联系]
 * @param {} info
 */
OrderDetailHandler.settingPageCtlStatus = function(info){
	// 存储订单在不同状态下订制的功能按钮字符编码
	var purArrayODetail = new Array();
	
	var goodsTitle = "";
	var consigneeTitle = "";
	
	OrderDetailHandler.allStatus.boiOrder = info.boiOrder;
	OrderDetailHandler.allStatus.boiPay = info.boiPay;
	OrderDetailHandler.allStatus.boiShip = info.boiShip;
	
	// 下单完成时
	if(info.boiOrder == 0 && info.boiPay == 0 && info.boiShip == 0){
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.queRBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.fuKBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.quXBtn);
	}
	// 确认完成时
	else if(info.boiOrder == 1 && info.boiPay == 0 && info.boiShip == 0){
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.fuKBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.quXBtn);
	}
	// 付款完成时
	else if(info.boiOrder == 1 && info.boiPay == 1 && info.boiShip == 0){
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.peiHBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.faHDBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.quXBtn);
	}
	// 配货完成时
	else if(info.boiOrder == 1 && info.boiPay == 1 && info.boiShip == 1){
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.faHDBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.quXBtn);
	}
	// 发货完成时
	else if(info.boiOrder == 1 && info.boiPay == 1 && info.boiShip == 3){
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.shouHBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.tuiHBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.wuFLXBtn);
	}
	// 退货
	else if(info.boiOrder == 1 && info.boiPay == 1 && info.boiShip == 5){
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.shiXBtn);
	}
	// 无法联系
	else if(info.boiOrder == 1 && info.boiPay == 1 && info.boiShip == 6){
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.faHDBtn);
		purArrayODetail.push(OrderDetailHandler.purJsonOdetail.shiXBtn);
	}
	
	// 加载订制的功能权限按钮
	OrderDetailHandler.loadPurviewBtn(purArrayODetail);
	
	// 隐藏操作表格
	if(info.boiOrder == 2 || info.boiOrder == 4 
			|| info.boiShip == 2 || info.boiShip == 4){
		OrderDetailHandler.operatingPanel.hide();
	}
	
	// 设置商品信息面板标题
	if(info.boiOrder != 2 && info.boiShip < 1 ){
		goodsTitle = "[<a href='#' onclick='OrderDetailHandler.editOrderGoods();'>编辑</a>]";
	}
	// 设置收货人信息面板标题
	if(info.boiOrder != 2 && info.boiShip < 3 ){
		consigneeTitle = "[<a href='#' onclick='OrderDetailHandler.editConsigneeInfo();'>编辑</a>]";
	}
	
	OrderDetailHandler.goodsPanel.setTitle("商品信息" + goodsTitle);
	OrderDetailHandler.consigneePanel.setTitle("收货人信息" + consigneeTitle);
}

/**
 * 加载区域名称处理程序
 * @param {} regionId
 * @param {} level
 */
OrderDetailHandler.loadRegionName = function(regionId, level){
	$.ajax({
		url : OrderDetailHandler.mgrData.loadRegionInfoUrl(regionId),
		cache : false,
		dataType : 'json',
		success : function(text) {
			if(text != null && text != ""){
				if(level == 1){
					$("#boiCountry").html("[" + text.bdrName);
				}else if(level == 2){
					$("#boiProvince").html(text.bdrName);
				}else if(level == 3){
					$("#boiCity").html(text.bdrName);
				}else if(level == 4){
					$("#boiDistrict").html(text.bdrName + "]");
				}
			}
		},
		error: function(){
			MiniuiTools.miniError("系统提示","数据加载出错！");
		}
	})
}

/**
 * 加载订单信息
 */
OrderDetailHandler.loadOrderInfo = function(){
	$.ajax({
		url : OrderDetailHandler.mgrData.loadOrderInfoUrl(__boiId),
		cache : false,
		dataType : 'json',
		success : function(text) {
			if(text != null && text != ""){
				OrderDetailHandler.settingPageCtlStatus(text);

				var indigoStr  = "<font style='color:#4B0082'>";
		        var medblueStr = "<font style='color:#0000CD'>";
		        var greenStr   = "<font style='color:#008000'>"; 
		        var orgedStr   = "<font style='color:#FF0066'>";
		        var redStr     = "<font style='color:#FF0000'>";
		        var fontLas    = "</font>";
     
				var boiOHtml = OrderDetailHandler.mgrData.boiOrderData[text.boiOrder + 1].text;
				var boiPHtml   = OrderDetailHandler.mgrData.boiPayData[text.boiPay + 1].text;
				var boiSHtml  = OrderDetailHandler.mgrData.boiShipData[text.boiShip + 1].text;
				
				if(text.boiOrder == 0){
					boiOHtml = greenStr + boiOHtml + fontLas;
				}else if(text.boiOrder == 1){
					boiOHtml = indigoStr + boiOHtml + fontLas;
				}else if(text.boiOrder == 2 || text.boiOrder == 4){
					boiOHtml = redStr + boiOHtml + fontLas;
				}else if(text.boiOrder == 3){
					boiOHtml = medblueStr + boiOHtml + fontLas;
				}
			
				if(text.boiPay == 0){
					boiPHtml = greenStr + boiPHtml + fontLas;
				}else if(text.boiPay == 1){
					boiPHtml = medblueStr + boiPHtml + fontLas;
				}else if(text.boiPay == 2){
					boiPHtml = redStr + boiPHtml + fontLas;
				}
				
				if(text.boiShip == 0){
					boiSHtml = greenStr + boiSHtml + fontLas;
				}else if(text.boiShip == 1 || text.boiShip == 2){
					boiSHtml = indigoStr + boiSHtml + fontLas;
				}else if(text.boiShip == 3){
					boiSHtml = orgedStr + boiSHtml + fontLas;
				}else if(text.boiShip == 4){
					boiSHtml = medblueStr + boiSHtml + fontLas;
				}else if(text.boiShip == 5 || text.boiShip == 6){
					boiSHtml = redStr + boiSHtml + fontLas;
				}
				
				var boiPtimeStr = "未付款";
				var boiStimeStr = "未发货";
				var boiInvnum   = "未发货";
				var boiCtimeStr = "未完成";
				
				if(text.boiPtime != null && text.boiPtime != "") boiPtimeStr = XMAppUtils.changeDateToDateTimeStr(text.boiPtime, false);
				if(text.boiStime != null && text.boiStime != "") boiStimeStr = XMAppUtils.changeDateToDateTimeStr(text.boiStime, false);
				if(text.boiCtime != null && text.boiCtime != "") boiCtimeStr = XMAppUtils.changeDateToDateTimeStr(text.boiCtime, false);
				if(text.boiInvnum != null && text.boiInvnum != "") boiInvnum = text.boiInvnum;

				// 基本信息
				$("#boiOsn").html(text.boiOsn);
				$("#boiOrder").html(boiOHtml + ",");
				$("#boiPay").html(boiPHtml + ",");
				$("#boiShip").html(boiSHtml);
				$("#boiPaymodename").html(text.boiPaymodename);
				$("#boiDeliverymode").html(text.boiDeliverymode);
				$("#boiOtime").html(XMAppUtils.changeDateToDateTimeStr(text.boiOtime, false));
				$("#boiPtime").html(boiPtimeStr);
				$("#boiStime").html(boiStimeStr);
				$("#boiInvnum").html(boiInvnum);
				$("#boiCtime").html(boiCtimeStr);
				
				// 存储收货人姓名
				OrderDetailHandler.gbConsignee = text.boiConsignee;
				
				// 收货人信息
				$("#boiConsignee").html(text.boiConsignee);
				$("#boiPhone").html(text.boiPhone);
				$("#boiMobile").html(text.boiMobile);
				$("#boiDetail").html(text.boiDetail);
				$("#boiZipcode").html(text.boiZipcode);
				$("#boiUremark").html(text.boiUremark);
				$("#boiBest").html(text.boiBest);
				OrderDetailHandler.loadRegionName(text.boiCountry, 1);
				OrderDetailHandler.loadRegionName(text.boiProvince, 2);
				OrderDetailHandler.loadRegionName(text.boiCity, 3);
				OrderDetailHandler.loadRegionName(text.boiDistrict, 4);
				
				// 费用信息
				$("#boiGpay").html(parseFloat(text.boiGpay).toFixed(2));
				$("#boiSpay").html(parseFloat(text.boiSpay).toFixed(2));
				$("#boiCouponpay").html(parseFloat(text.boiCouponpay).toFixed(2));
				$("#boiTpay").html(parseFloat(text.boiTpay).toFixed(2));
				
			}
		},
		error: function(){
			MiniuiTools.miniError("系统提示","数据加载出错！");
		}
	});
}

/**
 * 加载用户信息
 */
OrderDetailHandler.loadMemberInfo = function(){
	$.ajax({
		url : OrderDetailHandler.mgrData.loadMemberInfoUrl(__bmbId),
		cache : false,
		dataType : 'json',
		success : function(text) {
			var bmbNick = "匿名用户";
			
			if(text != null && text != ""){
				bmbNick = text.bmbNick; 
			}

			// 订购人
			$("#bmbNick").html(bmbNick);
		},
		error: function(){
			MiniuiTools.miniError("系统提示","数据加载出错！");
		}
	});
}

/**
 * 加载商品订购列表
 */
OrderDetailHandler.loadOrderGoods = function(){
	OrderDetailHandler.goodsListGrid.url = OrderDetailHandler.mgrData.loadOrderGoodsUrl(__boiId);
	OrderDetailHandler.goodsListGrid.load();
}

/**
 * 加载订单日志列表
 */
OrderDetailHandler.loadOrderLogs = function(){
	OrderDetailHandler.orderLogGrid.url = OrderDetailHandler.mgrData.loadOrderLogsUrl(__boiId);
	OrderDetailHandler.orderLogGrid.load();
}

/**
 * 初始化数据
 */
OrderDetailHandler.init = function(){
	OrderDetailHandler.initPageCtlStatus();
	OrderDetailHandler.loadOrderInfo();
	OrderDetailHandler.loadMemberInfo();
	OrderDetailHandler.loadOrderGoods();
	OrderDetailHandler.loadOrderLogs();
};  

OrderDetailHandler.init();

/**
 * 重载相关区域
 */
OrderDetailHandler.reloadRelation = function(){
	// 重新设置页面控件以便重新订制
	OrderDetailHandler.initPageCtlStatus();
	// 刷新基本信息
	OrderDetailHandler.loadOrderInfo();
	// 刷新操作日志
	OrderDetailHandler.loadOrderLogs();
	// 清空操作日志文本域
	OrderDetailHandler.clearLolOremark();
}

/**
 * 展开订单取消窗口
 * @param {} boiId
 * @param {} disposeType
 * @param {} lolOremark
 * @param {} isPaid 是否已付款
 */
OrderDetailHandler.showCancelWin = function(boiId, disposeType, lolOremark, isPaid){
	miniWin.afreshNewWin();
	miniWin.setParams(363, 315, "取消订单"); 
	miniWin.setOption("bodyStyle","padding:0px;");

	miniWin.load("cancelOrder.jsp",function(){
		var iframe = miniWin.getIFrameEl();
        var data = {
        	boiId: boiId, 
        	disposeType: disposeType, 
        	lolOremark: lolOremark,
        	isPaid: isPaid,
        	isBatch: false
        };
        
        iframe.contentWindow.CancelOrderHandler.passData(data);
	},function(action){
		if(action == "save"){
			OrderDetailHandler.reloadRelation();
		}
	});
	
	miniWin.show();
}

/**
 * 订单状态处理程序
 * @param {} disposeType
 */
OrderDetailHandler.disposeOrder = function(disposeType){
	var lolOremark = OrderDetailHandler.$lolOremark.val();
	
	if(disposeType == OrderDetailHandler.mgrData.fuKBtn
			|| disposeType == OrderDetailHandler.mgrData.tuiHBtn
				|| disposeType == OrderDetailHandler.mgrData.wuFLXBtn
					|| disposeType == OrderDetailHandler.mgrData.shiXBtn){
		if(lolOremark == ""){
			MiniuiTools.miniWarning("系统提示", "请填写操作备注！");
			OrderDetailHandler.$lolOremark.focus();
			return;
		}
	
	}else if(disposeType == OrderDetailHandler.mgrData.quXBtn){
		if(OrderDetailHandler.allStatus.boiPay == 0){       // 付款前的取消操作
			OrderDetailHandler.showCancelWin(__boiId, disposeType, lolOremark, false);
		}else if(OrderDetailHandler.allStatus.boiPay == 1){ // 付款后的取消操作
			OrderDetailHandler.showCancelWin(__boiId, disposeType, lolOremark, true);
		}
		
		return;
	}
	
	$.ajax({
        url: OrderDetailHandler.mgrData.disposeOrderUrl(),
        type: "post",
        dataType : 'json',
        data: {
    		boiId: __boiId, 
    		disposeType: disposeType,
    		operateUType: gbOperateUType,
    		operateUser: gbOperateUser,
    		operateIp: gbOperateIp, 
    		lolOremark: OrderDetailHandler.$lolOremark.val()
        },
        cache: false,
        success: function (text) {
        	OrderDetailHandler.reloadRelation();
        },
        error: function (jqXHR, textStatus, errorThrown) {
        	MiniuiTools.miniError("系统提示", "操作失败！" + jqXHR.responseText);
        },
		complete : function(){
			OrderDetailHandler.hiddenForm.unmask();
		}
    });
    
    OrderDetailHandler.hiddenForm.loading();
}

/**
 * 返回按钮点击事件处理程序
 */
OrderDetailHandler.returnOrderList = function(){
	window.location.href = "orderList.jsp";
}

/**
 * 商品列表表格绘画事件处理程序
 */
OrderDetailHandler.goodsListGrid.on("drawcell", function(e) {
	 var record = e.record;
     var column = e.column;
     var value = e.value;
     var innerHtml = "";
	
	switch (column.field) {
		case "bogName":
		{
			if (value != ""){
				innerHtml = value + "[" + record.bgbName + "]";
			}
			break;
		}
		case "bogPrice":
		{
			innerHtml = "￥0.00元";
			if (value != ""){
				innerHtml = "￥" + parseFloat(value).toFixed(2) + "元";
			}
			break;
		}
		case "bogAttprice":
		{
			innerHtml = "￥0.00元";
			if (value != ""){
				innerHtml = "￥" + parseFloat(value).toFixed(2) + "元";
			}
			break;
		}
		case "bogTotal":
		{
			innerHtml = "￥0.00元";
			if (value != ""){
				innerHtml = "￥" + parseFloat(value).toFixed(2) + "元";
			}
			break;
		}
	}
	
	if (innerHtml) e.cellHtml = innerHtml;
});

/**
 * 日志列表表格绘画事件处理程序
 */
OrderDetailHandler.orderLogGrid.on("drawcell", function(e) {
	 var record = e.record;
     var column = e.column;
     var value = e.value;
     var innerHtml = "";
	
	switch (column.field) {
		case "lolTime":
		{
			if (value != ""){
				innerHtml = XMAppUtils.changeDateToDateTimeStr(value);
			}
			break;
		}
	}
	
	if (innerHtml) e.cellHtml = innerHtml;
});

/**
 * 编辑收货人信息按钮点击事件处理程序
 */
OrderDetailHandler.editConsigneeInfo = function(){
	if (!MiniuiTools.hasPurview(OrderDetailHandler.purJsonOdetail.editConsignee)) {
		mini.showMessageBox({title:"提示",message:"糟糕，您没有权限访问！",iconCls:"mini-messagebox-info",buttons: ["ok"]});
		return;
	}
	
	var title = 
	miniWin.afreshNewWin();
	miniWin.setParams(540, 323, "编辑[<font color='#0000FF'>" + OrderDetailHandler.gbConsignee + "</font>]的收货信息"); 
	miniWin.setOption("bodyStyle","padding:0px;");

	miniWin.load("editConsigneeInfo.jsp",function(){
		var iframe = miniWin.getIFrameEl();
        var data = {
        	boiId: __boiId
        };
        
        iframe.contentWindow.ConsigneeInfoHandler.passData(data);
	},function(action){
		if(action == "save"){
			OrderDetailHandler.loadOrderInfo();
			OrderDetailHandler.loadOrderLogs();
		}
	});
	
	miniWin.show();
}

/**
 * 编辑商品信息按钮点击事件处理程序
 */
OrderDetailHandler.editOrderGoods = function(){
	if (!MiniuiTools.hasPurview(OrderDetailHandler.purJsonOdetail.editOrderGoods)) {
		mini.showMessageBox({title:"提示",message:"糟糕，您没有权限访问！",iconCls:"mini-messagebox-info",buttons: ["ok"]});
		return;
	}
	
	window.location.href = "editOrderGoods.jsp?boiId=" + __boiId + "&bmbId=" + __bmbId;
}

